<template>
  <div>
    <el-select v-if="type == 'select'" v-model="innerValue"
               :placeholder="$attrs.placeholder || '请选择字典值'"
               :clearable="$attrs.clearable != null ? $attrs.clearable : true"
               :multiple="multiple"
               @change="onchange"
    >
      <el-option
        v-for="dict in innerOptions"
        :key="dict.value"
        :label="dict[labelKey]"
        :value="dict[valueKey]"
      />
    </el-select>
    <el-radio-group v-if="type == 'radio'" v-model="innerValue">
      <el-radio
        v-for="dict in innerOptions"
        :key="dict.value"
        :label="dict[valueKey]"
      >{{ dict[labelKey] }}
      </el-radio>
    </el-radio-group>
  </div>
</template>

<script>

export default {
  name: "DictSelect",
  props: {
    options: {
      type: Array,
      default: null,
    },
    type: {
      default: 'select'
    },
    dictType: String,
    value: [Number, String, Array],
    multiple: {
      type: Boolean,
      default: false
    },
    valueKey: {
      default: 'value'
    },
    labelKey: {
      default: 'label'
    }
  },
  data() {
    return {
      innerOptions: this.$props.options || [],
      innerValue: null
    }
  },
  methods: {
    initInnerValue() {
      let v = this.value
      if (v == null || v == 'undefined') {
        this.innerValue = this.multiple ? [] :null
        return;
      }
      if (!this.multiple) {
        this.innerValue = String(v)
        return;
      }
      const values = v.split(',')
      if (values.length > 0) this.innerValue = values
    },
    onDictReady() {
      this.innerOptions = this.dict.type[this.dictType]
      // this.values = this.value.split(",")
    },
    async onchange(value) {
      const v = await this.innerOptions.find(i => i[this.valueKey] == value)
      this.$emit("change", value, v)
    }
  },
  watch: {
    innerValue(newData, oldData) {
      if (newData == oldData) return
      if (this.multiple) {
        newData = newData.length  ? newData.join(",") : null
      }
      this.$emit('input', newData);
    },
    value: {
      handler(newData) {
        this.initInnerValue();
      },
      immediate: true
    }
  },
  beforeCreate() {
    let dictType = this.$options.propsData.dictType;
    if (dictType) {
      this.$options.dicts = [dictType];
    }
  }
};
</script>
<style scoped lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}
</style>
